package com.dream.myqiyi.search;
/***
 * @modify
 * ===>2013.8.5
 *    1.修改通用性
 * **/

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.py.app.NiActivity;

import com.cloud.httputil.HttpUtil;
import com.dream.myqiyi.R;
import com.dream.myqiyi.search.GudingzichanActivity.DataThread;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class XianjinActivity extends Activity {

	private static final String TAG="XianJin";
    private static final int NETWORKWRONG=0x20000;
    private static final int GETDATASUC=0x3001;
    private static final int SHOWINFO=0x3002;
    private int pageCount=0;
    private int current_page=1;
    private List<XianjinObject> showlist=new ArrayList<XianjinObject>();
    private HashMap<String ,String> methods;
    private ListView gdlistView;
    private TextView countpage;
    private Spinner jumppage;
    private JSONObject jsonObject;
    private XianjinAdapter adapter;
    private ArrayAdapter<Integer> pageAdapter ;
    private ProgressBar progressBar;
    private List<Integer> pagearray=new ArrayList<Integer>();
    private int listtype=10;//默认为10
    Dialog jsonDialog = null;
	TextView jsonTextView = null, jsonTitle = null;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.caiwu_view);
		
		gdlistView = (ListView) findViewById(R.id.listview_cw);//你固定资产里面也是
		TextView textView1 = (TextView) findViewById(R.id.numtext3);
		TextView textView2 = (TextView) findViewById(R.id.nametext3);
		TextView textView3 = (TextView) findViewById(R.id.unitnotext3);

		textView1.setText(R.string.summary);
		textView2.setText(R.string.money);
		textView3.setText(R.string.unitname);
		

		//gdlistView = (ListView) findViewById(R.id.listview_cw);
        jumppage=(Spinner)findViewById(R.id.jumppage);
        Button nextbutton=(Button)findViewById(R.id.nextpagebutton);
        nextbutton.setOnClickListener(listener);
        Button lastbutton=(Button)findViewById(R.id.lastpagebutton);
        lastbutton.setOnClickListener(listener);
        countpage=(TextView)findViewById(R.id.showcountpage);
        progressBar=(ProgressBar)findViewById(R.id.progressBar_caiwu);
        pagearray.add(1);
        System.out.println("===========现金银行存款============");
        

		pageAdapter = new ArrayAdapter<Integer>(this,
                 android.R.layout.simple_spinner_item, pagearray);
        pageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    	 jumppage.setAdapter(pageAdapter);
    	
    	 jumppage.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
			
				TextView textView=(TextView)arg1;
                textView.setTextColor(Color.BLACK);
                textView.setTextSize(20);
                textView.setGravity(Gravity.CENTER);
                textView.setText(arg2+"");
                if(!pagearray.isEmpty()){
                	current_page=pagearray.get(arg2);
                	textView.setText(current_page+"");
                	methods.put("pageIndex", current_page+"");
                	progressBar.setVisibility(View.VISIBLE);
                	new Thread(new DataThread()).start();
                }
				
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {}
    		
		});
    	 
    	 methods = new HashMap<String, String>();
         methods.put("sessionid", NiActivity.SESSIONID);
         methods.put("unitno", NiActivity.UNITNO);
         methods.put("planyear", "2013");
         //====>2013.8.5
         String listtyString=getIntent().getStringExtra("listType");
         if(listtyString!=null){
        	 methods.put("listType", listtyString);
        	 listtype=Integer.parseInt(listtyString);
         }else{
        	 methods.put("listType", "10");
         }
         //<===2013.8.5
         adapter=new XianjinAdapter(this,showlist);
 		 gdlistView.setAdapter(adapter);
         gdlistView.setOnItemClickListener(new OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
             	 Log.i(TAG, "onItemclick"+i);
                  showJsonDialog(showlist.get(i));
             }
         });
 	}
	
	/**
	    * show dialog
	    * */
		private void showJsonDialog(XianjinObject xianjinObject) {
			if (jsonDialog == null) {
				jsonDialog = new Dialog(this,R.style.bktransparentDialog);
				jsonDialog.setCancelable(true);
				jsonDialog.setCanceledOnTouchOutside(false);
				View v = View.inflate(this, R.layout.mydialog, null);
				jsonDialog.setContentView(v);
				jsonTextView = (TextView) v.findViewById(R.id.message);
				jsonTitle = (TextView) v.findViewById(R.id.title);
				v.findViewById(R.id.positiveButton).setOnClickListener(
						new OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								if (jsonDialog != null) {
									jsonDialog.dismiss();
								}
							}
						});
			}
			//===>2013.8.5
			String title=getString(R.string.xianjin);
			switch (listtype) {
			case 1:
				title=getString(R.string.gexiangshouru);
				break;
			case 2:
				title=getString(R.string.gexiangzhichu);
				break;
			case 3:
				title=getString(R.string.zhaiquanzhaiw);
				break;
			case 4:
				title=getString(R.string.shouyifenpei);
				break;
			case 5:
				title=getString(R.string.chanpingwuz);
				break;
			case 6:
				title=getString(R.string.qitazijin);
				break;
			case 7:
				title=getString(R.string.nongyezichan);
				break;
			case 8:
				title=getString(R.string.duiwaitouz);
				break;
			case 9:
				title=getString(R.string.qitatouz);
				break;
			case 10:
				title=getString(R.string.xianjin);
				break;
			}
	        jsonTitle.setText(title);
	        //<===2013.8.5
	        String content=getString(R.string.summary)+":"+xianjinObject.getSummary()+"\n"
	                      +getString(R.string.money)+":"+xianjinObject.getMoney()+"\n"
	                      +getString(R.string.unitname)+":"+xianjinObject.getUnitname()+"\n"
	                      +getString(R.string.unitno)+":"+xianjinObject.getUnitno()+"\n"
	                      +getString(R.string.sortword)+":"+xianjinObject.getSortword()+"\n"
	                      +getString(R.string.voucherno)+":"+xianjinObject.getVoucherno()+"\n"
	                      +getString(R.string.voucherkey)+":"+xianjinObject.getVoucherkey()+"\n"
	                      +getString(R.string.direction)+":"+xianjinObject.getDirection()+"\n"
	                      ;
			jsonTextView.setText(content);
			jsonDialog.show();
		}
         
//		final ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
//
//		try {
//			JSONObject resultJObject = new JSONObject(result);
//			JSONArray itemArray = resultJObject.getJSONArray("items");
//			for (int i = 0; i < itemArray.length(); i++) {
//				JSONObject assets = new JSONObject(itemArray.opt(i).toString());
//
////				String obtaindate = assets.getString("obtaindate");
////				System.out.println(obtaindate);
//				
//				String code = assets.getString("summary");
//				String name = assets.getString("money");
//				String unitname = assets.getString("unitname");
//				String unitno = assets.getString("unitno");
//				String sortword = assets.getString("sortword");
//				String voucherno = assets.getString("voucherno");
//				String voucherkey = assets.getString("voucherkey");
//				String direction = assets.getString("direction");
////				String price = assets.getString("price");
////				String owner = assets.getString("owner");
////				String address = assets.getString("address");
//				
//				System.out.println(code + "==" + name + "==" + unitname );
////						+ "==" + type + "==" + amount + "==" + status);
////				
//				HashMap<String, Object> listmap = new HashMap<String, Object>();
//				listmap.put("numtext", code);
//				listmap.put("name", name);
//				listmap.put("unitnotext", unitname);
//				listmap.put("unitno", unitno);
//				listmap.put("sortword", sortword);
//				listmap.put("voucherno", voucherno);
//				listmap.put("voucherkey", voucherkey);
//				listmap.put("direction", direction);
////				listmap.put("price", price);
////				listmap.put("owner", owner);
////				listmap.put("address", address);
//				listItem.add(listmap);
//			}
//
//		} catch (JSONException e) {
//			// TODO Auto-generated catch block
//			Log.i(TAG, e.toString());
//			e.printStackTrace();
//		}
//		SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,
//				R.layout.listlayout, 
//				new String[] { "numtext", "name","unitnotext" }, 
//				new int[] { R.id.numtext,R.id.nametext, R.id.unitnotext });
//
//		gdlistView.setAdapter(listItemAdapter);
//
//		gdlistView.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
//					long arg3) {
//				String str1 = "概要信息：" + listItem.get(arg2).get("numtext") + "\n"
//						+ "额度：" + listItem.get(arg2).get("name") + "\n"
//						+
//						"所属村组：" + listItem.get(arg2).get("unitnotext") +"\n"
//						+ "帐套编号：" + listItem.get(arg2).get("unitno") +"\n"
//						+ "类别：" + listItem.get(arg2).get("sortword") +"\n"
//						+ "凭证号：" + listItem.get(arg2).get("voucherno") +"\n"
//						+ "voucherkey：" + listItem.get(arg2).get("voucherkey") +"\n"
//						+ "direction：" + listItem.get(arg2).get("direction") +"\n"
////						+ "单价：" + listItem.get(arg2).get("price") +"\n"
////						+ "责任人：" + listItem.get(arg2).get("owner") +"\n"
////						+ "存放地点：" + listItem.get(arg2).get("address") +"\n"
//						;
//				showJsonDialog(listItem.get(arg2).get("numtext").toString(), str1);
//				System.out.println("=======click"+arg2+"======");
//			}
//		});
//	}

		/**
		 * DataThread is use to get data form service 
		 * */
		class DataThread implements Runnable{

			@Override
			public void run() {
				 try{
				    jsonObject=HttpUtil.xianjin(methods);
				     if(jsonObject!=null){
				           handler.sendEmptyMessage(SHOWINFO);
				       }else{
				            handler.sendEmptyMessage(NETWORKWRONG);
				        }
				    }catch (Exception e){
				         Log.i(TAG,e.toString());
				         handler.sendEmptyMessage(NETWORKWRONG);
				    }
				
			}
			
		}
		
		 /**
		 * get data from xml file method
		 * **/
	    public  void getdata(){   	   	
	    	showlist.clear();
	        try {
	            JSONArray itemArray = jsonObject.getJSONArray("items");
	            XianjinObject Object;
	            for (int i = 0; i < itemArray.length(); i++) {

	                JSONObject assets = new JSONObject(itemArray.opt(i).toString());
	                Object=new XianjinObject();
	                Object.setSummary(assets.getString("summary"));
	                Object.setMoney(assets.getString("money"));
	                Object.setUnitname(assets.getString("unitname"));
	                Object.setUnitno(assets.getString("unitno"));
	                Object.setSortword(assets.getString("sortword"));
	                Object.setVoucherno(assets.getString("voucherno"));
	                Object.setVoucherkey(assets.getString("voucherkey"));
	                Object.setDirection(assets.getString("direction"));
	                showlist.add(Object);
	            }
	        } catch (JSONException e) {
			  Log.i(TAG, e.toString());
	            e.printStackTrace();
	        }
	    }
	    Handler handler=new Handler(){
	        @Override
	        public void handleMessage(Message msg) {
	        	progressBar.setVisibility(View.GONE);
	            switch (msg.what){
		            case SHOWINFO:
		            	try {
		            		if(pageCount==0){
		            			String pagecountstring=jsonObject.getString("pageCount");
		            			pageCount=Integer.parseInt(pagecountstring);
		            			countpage.setText(String.format(getString(R.string.countpage),pagecountstring));//展示总页数
		            		    pagearray.clear();
		            		    for(int i=1;i<=pageCount;i++){
		            		    	pagearray.add(i);
		            		    }
		            		    pageAdapter.notifyDataSetChanged();
		            		}
		            		getdata();
							adapter.notifyDataSetChanged();
						} catch (Exception e) {
							e.printStackTrace();
						}
		            	break;
	                case NETWORKWRONG:
	                    Toast.makeText(XianjinActivity.this, R.string.networkwrong, Toast.LENGTH_SHORT).show();
	                    break;
	            }
	            super.handleMessage(msg);
	        }
	    };
	    
	   
	   
	    /**
	     * button function
	     * ***/
	    OnClickListener listener=new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.lastpagebutton:
					if(current_page>1){
						current_page--;
						 methods.put("pageIndex", current_page+"");
						 jumppage.setSelection(current_page-1);
						// progressBar.setVisibility(View.VISIBLE);
						// new Thread(new DataThread()).start();
					}
					break;
				case R.id.nextpagebutton:
				   if(current_page<pageCount){
					   current_page++;
					   methods.put("pageIndex", current_page+"");
					   jumppage.setSelection(current_page-1);
					 //  progressBar.setVisibility(View.VISIBLE);
					 //  new Thread(new DataThread()).start();
				   }
					break;

				default:
					break;
				}
				
			}
		};

		
	}		
//	Dialog jsonDialog = null;
//	TextView jsonTextView = null, jsonTitle = null;
//
//	private void showJsonDialog(String title, String json) {
//		if (jsonDialog == null) {
//			jsonDialog = new Dialog(this);
//			jsonDialog.setCancelable(true);
//			jsonDialog.setCanceledOnTouchOutside(false);
//			View v = View.inflate(this, R.layout.mydialog, null);
//			jsonDialog.setContentView(v);
//			jsonTextView = (TextView) v.findViewById(R.id.message);
//			jsonTitle = (TextView) v.findViewById(R.id.title);
//			v.findViewById(R.id.positiveButton).setOnClickListener(
//					new OnClickListener() {
//
//						@Override
//						public void onClick(View v) {
//							// TODO Auto-generated method stub
//							if (jsonDialog != null) {
//								jsonDialog.dismiss();
//							}
//						}
//					});
//		}
//		jsonTextView.setText(json);
//		jsonTitle.setText(title);
//		jsonDialog.show();
//	}
//}




